<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

/**
 * 汤药管理控制器
 */
class Formula extends Base
{
    /**
     * 获取汤药列表
     */
    public function index()
    {
        $page = input('page', 1);
        $limit = input('limit', 20);
        $keyword = input('keyword', '');

        $where = [];
        if (!empty($keyword)) {
            $where[] = [
                'name_zh_cn|name_en_us|name_ja_jp|name_be_by',
                'like',
                '%' . $keyword . '%'
            ];
        }

        // 优化查询：只查询必要字段，减少数据传输
        $list = Db::name('formulas')
            ->field('id,name_zh_cn,name_en_us,name_ja_jp,name_be_by,description_zh_cn,main_symptom_ids,side_symptom_ids,sort_order,is_active,created_at,updated_at')
            ->where($where)
            ->order('sort_order asc, id asc')
            ->paginate($limit, false, ['page' => $page]);

        // 优化：批量获取症状信息，避免N+1查询
        $items = $list->items();
        if (!empty($items)) {
            // 收集所有症状ID
            $allSymptomIds = [];
            foreach ($items as $item) {
                if (!empty($item['main_symptom_ids'])) {
                    $mainIds = explode(',', $item['main_symptom_ids']);
                    $allSymptomIds = array_merge($allSymptomIds, $mainIds);
                }
                if (!empty($item['side_symptom_ids'])) {
                    $sideIds = explode(',', $item['side_symptom_ids']);
                    $allSymptomIds = array_merge($allSymptomIds, $sideIds);
                }
            }

            // 去重并批量查询所有症状
            $allSymptomIds = array_unique(array_filter($allSymptomIds));
            $allSymptoms = [];
            if (!empty($allSymptomIds)) {
                $symptomsData = Db::name('symptoms')
                    ->alias('s')
                    ->join('symptom_categories sc', 's.category_id = sc.id')
                    ->whereIn('s.id', $allSymptomIds)
                    ->field('s.id,s.name_zh_cn,s.name_en_us,s.name_ja_jp,s.name_be_by,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
                    ->select();

                // 构建症状ID到症状信息的映射
                foreach ($symptomsData as $symptom) {
                    $allSymptoms[$symptom['id']] = $symptom;
                }
            }

            // 为每个汤药分配对应的症状信息
            foreach ($items as &$item) {
                $item['main_symptoms'] = $this->getSymptomsByIdsFromCache($item['main_symptom_ids'], $allSymptoms);
                $item['side_symptoms'] = $this->getSymptomsByIdsFromCache($item['side_symptom_ids'], $allSymptoms);
            }
        }

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $items,
                'total' => $list->total(),
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 获取单个汤药
     */
    public function read()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        $formula = Db::name('formulas')->find($id);

        if (!$formula) {
            return json(['code' => 1, 'msg' => '数据不存在']);
        }

        // 补充症状信息
        $formula['main_symptoms'] = $this->getSymptomsByIds($formula['main_symptom_ids']);
        $formula['side_symptoms'] = $this->getSymptomsByIds($formula['side_symptom_ids']);

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $formula
        ]);
    }

    /**
     * 创建汤药
     */
    public function save()
    {
        $data = input('post.');

        // 定义允许插入的字段（只包含汤药表的字段）
        $allowedFields = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by',
            'description_zh_cn', 'description_en_us', 'description_ja_jp', 'description_be_by',
            'ingredients_zh_cn', 'ingredients_en_us', 'ingredients_ja_jp', 'ingredients_be_by',
            'usage_zh_cn', 'usage_en_us', 'usage_ja_jp', 'usage_be_by',
            'main_symptom_ids', 'side_symptom_ids',
            'sort_order', 'is_active'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }

        // 验证必填字段
        $required = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($filteredData[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }

        // 检查中文名称是否重复
        $existingFormula = Db::name('formulas')
            ->where('name_zh_cn', $filteredData['name_zh_cn'])
            ->find();
        if ($existingFormula) {
            return json(['code' => 1, 'msg' => '汤药名称"' . $filteredData['name_zh_cn'] . '"已存在']);
        }

        // 处理症状ID数组
        if (isset($filteredData['main_symptom_ids']) && is_array($filteredData['main_symptom_ids'])) {
            $filteredData['main_symptom_ids'] = implode(',', $filteredData['main_symptom_ids']);
        }
        if (isset($filteredData['side_symptom_ids']) && is_array($filteredData['side_symptom_ids'])) {
            $filteredData['side_symptom_ids'] = implode(',', $filteredData['side_symptom_ids']);
        }

        $filteredData['created_at'] = date('Y-m-d H:i:s');
        $filteredData['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('formulas')->insert($filteredData);

        if ($result) {
            return json(['code' => 0, 'msg' => '创建成功']);
        } else {
            return json(['code' => 1, 'msg' => '创建失败']);
        }
    }

    /**
     * 更新汤药
     */
    public function update()
    {
        $id = input('id');
        $data = input('post.');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 定义允许更新的字段（只包含汤药表的字段）
        $allowedFields = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by',
            'description_zh_cn', 'description_en_us', 'description_ja_jp', 'description_be_by',
            'ingredients_zh_cn', 'ingredients_en_us', 'ingredients_ja_jp', 'ingredients_be_by',
            'usage_zh_cn', 'usage_en_us', 'usage_ja_jp', 'usage_be_by',
            'main_symptom_ids', 'side_symptom_ids',
            'sort_order', 'is_active'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }

        // 验证必填字段
        $required = [
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($filteredData[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }

        // 检查中文名称是否重复（排除当前记录）
        $existingFormula = Db::name('formulas')
            ->where('name_zh_cn', $filteredData['name_zh_cn'])
            ->where('id', '<>', $id)
            ->find();
        if ($existingFormula) {
            return json(['code' => 1, 'msg' => '汤药名称"' . $filteredData['name_zh_cn'] . '"已存在']);
        }

        // 处理症状ID数组
        if (isset($filteredData['main_symptom_ids']) && is_array($filteredData['main_symptom_ids'])) {
            $filteredData['main_symptom_ids'] = implode(',', $filteredData['main_symptom_ids']);
        }
        if (isset($filteredData['side_symptom_ids']) && is_array($filteredData['side_symptom_ids'])) {
            $filteredData['side_symptom_ids'] = implode(',', $filteredData['side_symptom_ids']);
        }

        $filteredData['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('formulas')->where('id', $id)->update($filteredData);

        if ($result !== false) {
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 删除汤药
     */
    public function delete()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        $result = Db::name('formulas')->delete($id);

        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
    }

    /**
     * 批量删除
     */
    public function deleteMultiple()
    {
        $ids = input('ids');

        if (empty($ids) || !is_array($ids)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        $result = Db::name('formulas')->whereIn('id', $ids)->delete();

        if ($result) {
            return json(['code' => 0, 'msg' => '批量删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '批量删除失败']);
        }
    }

    /**
     * 根据症状查找汤药（原有功能的改进版）
     */
    public function findBySymptoms()
    {
        $symptomDesc = input('symptom_desc', '');

        if (empty($symptomDesc)) {
            return json(['code' => 1, 'msg' => '症状描述不能为空']);
        }

        // 解析输入的症状
        $inputSymptoms = array_map('trim', explode(',', $symptomDesc));
        $matchedFormulas = [];

        // 查找匹配的症状ID
        $symptomIds = [];
        foreach ($inputSymptoms as $symptomName) {
            $symptom = Db::name('symptoms')
                ->where('name_zh_cn|name_en_us|name_ja_jp|name_be_by', $symptomName)
                ->whereOr('keywords_zh_cn|keywords_en_us|keywords_ja_jp|keywords_be_by', 'like', '%' . $symptomName . '%')
                ->field('id')
                ->find();

            if ($symptom) {
                $symptomIds[] = $symptom['id'];
            }
        }

        if (empty($symptomIds)) {
            return json(['code' => 0, 'data' => [], 'msg' => '未找到匹配的症状']);
        }

        // 查找匹配的汤药
        $formulas = Db::name('formulas')->where('is_active', 1)->select();

        foreach ($formulas as $formula) {
            $matchScore = 0;
            $matchType = '';

            // 检查主症匹配
            if (!empty($formula['main_symptom_ids'])) {
                $mainSymptomIds = explode(',', $formula['main_symptom_ids']);
                $mainMatchCount = count(array_intersect($symptomIds, $mainSymptomIds));

                if ($mainMatchCount == count($mainSymptomIds) && $mainMatchCount == count($symptomIds)) {
                    // 完全匹配主症
                    $matchScore = 100;
                    $matchType = 'main_exact';
                } elseif ($mainMatchCount > 0) {
                    // 部分匹配主症
                    $matchScore = 50 + ($mainMatchCount / count($mainSymptomIds)) * 30;
                    $matchType = 'main_partial';
                }
            }

            // 检查兼症匹配（如果主症没有匹配）
            if ($matchScore == 0 && !empty($formula['side_symptom_ids'])) {
                $sideSymptomIds = explode(',', $formula['side_symptom_ids']);
                $sideMatchCount = count(array_intersect($symptomIds, $sideSymptomIds));

                if ($sideMatchCount > 0) {
                    $matchScore = 20 + ($sideMatchCount / count($sideSymptomIds)) * 20;
                    $matchType = 'side_partial';
                }
            }

            if ($matchScore > 0) {
                $formula['match_score'] = $matchScore;
                $formula['match_type'] = $matchType;
                $formula['main_symptoms'] = $this->getSymptomsByIds($formula['main_symptom_ids']);
                $formula['side_symptoms'] = $this->getSymptomsByIds($formula['side_symptom_ids']);
                $matchedFormulas[] = $formula;
            }
        }

        // 按匹配分数排序
        usort($matchedFormulas, function($a, $b) {
            return $b['match_score'] - $a['match_score'];
        });

        return json([
            'code' => 0,
            'data' => $matchedFormulas,
            'msg' => 'success'
        ]);
    }

    /**
     * 根据症状ID获取症状信息
     */
    private function getSymptomsByIds($symptomIds)
    {
        if (empty($symptomIds)) {
            return [];
        }

        $ids = explode(',', $symptomIds);
        $symptoms = Db::name('symptoms')
            ->alias('s')
            ->join('symptom_categories sc', 's.category_id = sc.id')
            ->whereIn('s.id', $ids)
            ->field('s.id,s.name_zh_cn,s.name_en_us,s.name_ja_jp,s.name_be_by,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
            ->select();

        return $symptoms;
    }

    /**
     * 从缓存中根据症状ID获取症状信息（优化版本）
     */
    private function getSymptomsByIdsFromCache($symptomIds, $symptomsCache)
    {
        if (empty($symptomIds)) {
            return [];
        }

        $ids = explode(',', $symptomIds);
        $symptoms = [];

        foreach ($ids as $id) {
            $id = trim($id);
            if (isset($symptomsCache[$id])) {
                $symptoms[] = $symptomsCache[$id];
            }
        }

        return $symptoms;
    }

    /**
     * 获取汤药统计信息
     */
    public function getStatistics()
    {
        $total = Db::name('formulas')->count();
        $active = Db::name('formulas')->where('is_active', 1)->count();
        $hasMainSymptoms = Db::name('formulas')->where('main_symptom_ids', '<>', '')->count();
        $hasSideSymptoms = Db::name('formulas')->where('side_symptom_ids', '<>', '')->count();

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'total' => $total,
                'active' => $active,
                'inactive' => $total - $active,
                'has_main_symptoms' => $hasMainSymptoms,
                'has_side_symptoms' => $hasSideSymptoms
            ]
        ]);
    }
}
